package com.comleader.baseproject.common.exception;

import com.comleader.baseproject.common.bean.response.CommonCode;
import com.comleader.baseproject.common.bean.response.ResponseCodeEnum;
import com.comleader.baseproject.common.bean.response.ResponseResult;
import com.google.common.collect.ImmutableMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author 张志航     
 * @version V1.0.0
 * @projectName xc-framework-parent
 * @title     ExceptionCatch   
 * @package    com.xuecheng.framework.exception  
 * @date   2019/12/16 11:26  
 * @explain
 */
@ControllerAdvice
public class ExceptionCatch {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionCatch.class);

    //使用EXCEPTIONS存放异常类型和错误代码的映射，ImmutableMap的特点的一旦创建不可改变，并且线程安全
    private static ImmutableMap<Class<? extends Throwable>, CommonCode> EXCEPTIONS;
    //使用builder来构建一个异常类型和错误代码的异常
    protected static ImmutableMap.Builder<Class<? extends Throwable>, CommonCode> builder = ImmutableMap.builder();

    @ExceptionHandler(CustomException.class)
    @ResponseBody
    //捕获可预知的CustomException异常
    public ResponseResult customException(CustomException e) {
        LOGGER.error("catch exception: {}\r\nexcecption", e.getMessage(), e);
        CommonCode resultCode = e.getResultCode();
        ResponseResult responseResult = new ResponseResult(resultCode);
        return responseResult;
    }


    @ExceptionHandler(Exception.class)
    @ResponseBody
    //捕获不可预知的Exception异常
    public ResponseResult exception(Exception e) {
        LOGGER.error("catch exception:{}", e.getMessage());
        if (EXCEPTIONS == null)  EXCEPTIONS = builder.build();

        final CommonCode resultCode = EXCEPTIONS.get(e.getClass());
        final ResponseResult responseResult;

        if (resultCode != null) responseResult = new ResponseResult(resultCode);
        else responseResult = new ResponseResult(ResponseCodeEnum.SERVER_ERROR);

        return responseResult;
    }

    static {
        // 这里可以加入一些基本类型的判断
        builder.put(HttpMessageNotReadableException.class,ResponseCodeEnum.INVALIDPARAM);
    }
}
